package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.service.VrManageService;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.service.dto.VrManageDTO;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.*;

/**
 * REST controller for managing VrManage.
 */
@RestController
@RequestMapping("/api")
public class VrManageResource {

    @Autowired
    private HttpServletRequest request;

    private final Logger log = LoggerFactory.getLogger(VrManageResource.class);

    private static final String ENTITY_NAME = "vrManage";

    private final VrManageService vrManageService;

    public VrManageResource(VrManageService vrManageService) {
        this.vrManageService = vrManageService;
    }

    /**
     * POST  /vr-manages : Create a new vrManage.
     *
     * @param vrManageDTO the vrManageDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new vrManageDTO, or with status 400 (Bad Request) if the vrManage has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/vr-manages")
    @Timed
    public ResponseEntity<VrManageDTO> createVrManage(@RequestBody VrManageDTO vrManageDTO) throws URISyntaxException {
        log.debug("REST request to save VrManage : {}", vrManageDTO);
        if (vrManageDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new vrManage cannot already have an ID")).body(null);
        }
        VrManageDTO result = vrManageService.save(vrManageDTO);
        return ResponseEntity.created(new URI("/api/vr-manages/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /vr-manages : Updates an existing vrManage.
     *
     * @param vrManageDTO the vrManageDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated vrManageDTO,
     * or with status 400 (Bad Request) if the vrManageDTO is not valid,
     * or with status 500 (Internal Server Error) if the vrManageDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/vr-manages")
    @Timed
    public ResponseEntity<VrManageDTO> updateVrManage(@RequestBody VrManageDTO vrManageDTO) throws URISyntaxException {
        log.debug("REST request to update VrManage : {}", vrManageDTO);
        if (vrManageDTO.getId() == null) {
            return createVrManage(vrManageDTO);
        }
        VrManageDTO result = vrManageService.save(vrManageDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, vrManageDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /vr-manages : get all the vrManages.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of vrManages in body
     */
    @GetMapping("/vr-manages")
    @Timed
    public List<VrManageDTO> getAllVrManages() {
        log.debug("REST request to get all VrManages");
        return vrManageService.findAll();
    }

    /**
     * GET  /vr-manages/:id : get the "id" vrManage.
     *
     * @param id the id of the vrManageDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the vrManageDTO, or with status 404 (Not Found)
     */
    @GetMapping("/vr-manages/{id}")
    @Timed
    public ResponseEntity<VrManageDTO> getVrManage(@PathVariable Long id) {
        log.debug("REST request to get VrManage : {}", id);
        VrManageDTO vrManageDTO = vrManageService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(vrManageDTO));
    }

    /**
     * DELETE  /vr-manages/:id : delete the "id" vrManage.
     *
     * @param id the id of the vrManageDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/vr-manages/{id}")
    @Timed
    public ResponseEntity<Void> deleteVrManage(@PathVariable Long id) {
        log.debug("REST request to delete VrManage : {}", id);
        vrManageService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    @PostMapping("/vr-manages/upload")
    @Timed
    public String fileUpload(@RequestParam MultipartFile file) {

        HashMap<String, Object> result = this.executeUploadFile(file);
        return JSON.toJSONString(result);
    }

    /**
     * 执行上传VR图片文件
     *
     * @param file
     * @return
     */
    private HashMap<String, Object> executeUploadFile(MultipartFile file) {
        HashMap<String, Object> result = new HashMap<>();
        if (!file.isEmpty()) {
            try {
                String oldFileName = file.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString() + oldFileName.substring(oldFileName.lastIndexOf("."));

                String rootPath = this.getApplicationPath();
                String folderPath = "attached" + File.separator + "VR";
                String path = rootPath + File.separator +  folderPath;
                File tempFile = new File(path);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                File newFile = new File(path + File.separator + newFileName);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();
                out.close();

                result.put("fileName", newFileName);
                result.put("filePath", path);
                result.put("fileType", oldFileName.substring(oldFileName.lastIndexOf(".") + 1));
                result.put("relativePath", (folderPath + File.separator + newFileName));
                result.put("status", true);
                result.put("message", "上传成功");
                return result;

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                result.put("status", false);
                result.put("message", "上传失败," + e.getMessage());
                return result;
            } catch (IOException e) {
                e.printStackTrace();
                result.put("status", false);
                result.put("message", "上传失败," + e.getMessage());
                return result;
            }
        } else {
            result.put("status", false);
            result.put("message", "上传失败，因为文件是空的.");
            return result;
        }
    }

    /**
     * 删除vr照片
     * @param vrPictures
     * @return
     */
    @PostMapping("/vr-manages/delVrPicture")
    @Timed
    public boolean delPictureByPath(@RequestBody List<String> vrPictures) {
        if(vrPictures.size() == 0){
            return true;
        }
        List<Boolean> delResultList = new ArrayList<>();
        String rootPath = getApplicationPath();
        for (int i=0; i< vrPictures.size(); i++){
            String picturePath = vrPictures.get(i);
            File tempFile = new File(rootPath + File.separator + picturePath);
            if (!tempFile.exists()) {
                continue;
            }
            boolean delResult = tempFile.delete();
            if(delResult){
                delResultList.add(true);
            }
        }
        return (delResultList.size() == vrPictures.size());
    }

    /**
     * 获取应用程序路径
     *
     * @return
     */
    private String getApplicationPath() {
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        return rootPath;
    }
}
